import json

from django.http import HttpResponse
import random
from redis import StrictRedis

redis = StrictRedis(host='localhost', port=6379, db=0, password=None)

def SSTF(disk, startnum):  # 计算当前值离左右哪个近，去近的那一边，递归，直到到边界，直接按顺序加上另外一边未访问的部分
    start = 0
    for i in range(10): # 寻找开始点
        if disk[i] > startnum:
            start = i
            break
    i = start - 1
    j = start
    ans = []
    while len(ans) < 10:
        if startnum - disk[i] < disk[j] - startnum:  # 左边小 往左移动
            ans.append(disk[i])
            startnum = disk[i]
            i -= 1
        else:
            ans.append(disk[j])
            startnum = disk[j]
            j += 1
        if i == -1:
            ans += disk[j:] # 到左边界，加上右边剩下的
            break
        if j == 10:
            ans += disk[:i + 1][::-1] # 到右边界，逆序加上左边剩下的
            break
    return ans

def SCAN(disk, startnum):
    left = [d for d in disk if d < int(startnum)][::-1]
    right = [d for d in disk if d >= int(startnum)]
    ans = right + left
    return ans

def CSCAN(disk, startnum):
    left = [d for d in disk if d < int(startnum)]
    right = [d for d in disk if d >= int(startnum)]
    ans = right + left
    return ans

def diskcalculate(request):
    if (request.method == 'POST'):
        concat = request.POST
        allnum = concat['allnum']
        if allnum == '':
            allnum = 200
        startnum = concat['startnum']
        if startnum == '':
            startnum = 100
        func = concat['func']
        timesrun = int(concat['timesrun'])
        # 连接redis 获取随机数，如果没有，则创建
        if redis.llen(str(allnum)) == 0:
            disk = [random.randint(0, int(allnum)) for _ in range(10)]
            for cut in disk:
                redis.rpush(str(allnum), cut)  # 以最大磁盘数作为健存随机值
        else:
            disk = []
            for i in range(redis.llen(str(allnum))):
                disk.append(int(redis.lindex(str(allnum), i)))
        origin = disk.copy()  # 浅拷贝
        ans = []
        if func == 'FCFS':
            ans = disk.copy()  # 浅拷贝
        disk.sort()
        if func == 'SSTF':
            ans = SSTF(disk, startnum)
        if func == 'SCAN':
            ans = SCAN(disk, startnum)
        if func == 'CSCAN':
            ans = CSCAN(disk, startnum)
        ans_beauti = str(ans).replace(",", "  -->  ")  # 优化结果显示
        origin_beauti = str(origin).replace(",", "  -->  ")
        print(origin_beauti)
        res = {"origin": origin_beauti,
               "ans": ans_beauti,
               "num": ans[timesrun],
               "all": allnum,
               }
        response = HttpResponse(json.dumps(res))
        response["Access-Control-Allow-Origin"] = "*"
        return response

def diskcompare(request):
    if (request.method == 'POST'):
        concat = request.POST
        allnum = concat['allnum']
        if allnum == '':
            allnum = 200
        startnum = concat['startnum']
        if startnum == '':
            startnum = 100
        if redis.llen(str(allnum)) == 0:
            disk = [random.randint(0, int(allnum)) for _ in range(10)]
            for cut in disk:
                redis.rpush(str(allnum), cut)  # 以最大磁盘数作为健存随机值
        else:
            disk = []
            for i in range(redis.llen(str(allnum))):
                disk.append(int(redis.lindex(str(allnum), i)))
        origin = disk.copy()
        ans1 = disk.copy()
        time1 = 0
        disk.sort()
        ans2 = SSTF(disk, startnum)
        time2 = 0
        for i in range(1, 10):
            time1 += abs(ans1[i] - ans1[i-1])
            time2 += abs(ans2[i] - ans2[i-1])
        ans3 = SCAN(disk, startnum)
        time3 = disk[-1] - startnum + disk[-1] - disk[0]
        ans4 = CSCAN(disk, startnum)
        time4 = allnum - startnum + ans4[-1]
        time_rank = {}
        time_rank["FCFS"] = time1
        time_rank["SSTF"] = time2
        time_rank["SCAN"] = time3
        time_rank["CSCAN"] = time4
        ans_dic = sorted(time_rank.items(), key=lambda x: x[1])
        time_index = [a[0] for a in ans_dic]

        ans = "轨道序列： " + str(origin).replace(",", "  -->  ") + "\n" \
            + "FCFS: " + str(ans1).replace(",", "  -->  ") + "\n" + "寻道总数: " + str(time1) + "  " + "平均寻道数: " + str(time1/10) + "\n" \
            + "SSTF: " + str(ans2).replace(",", "  -->  ") + "\n" + "寻道总数: " + str(time2) + "  " + "平均寻道数: " + str(time2/10) + "\n" \
            + "SCAN: " + str(ans3).replace(",", "  -->  ") + "\n" + "寻道总数: " + str(time3) + "  " + "平均寻道数: " + str(time3/10) + "\n" \
            + "CSCAN: " + str(ans4).replace(",", "  -->  ") + "\n" + "寻道总数: " + str(time4) + "  " + "平均寻道数: " + str(time4/10) + "\n" \
            + "按耗时排序： " + str(time_index).replace(",", "  -->  ")
        res = {"ans": ans}
        response = HttpResponse(json.dumps(res))
        response["Access-Control-Allow-Origin"] = "*"
        return response
